from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
from .neo4j_connection import graph
from .api_instance import api_instance

class ActionAskAboutHouse(Action):
    def name(self) -> Text:
        return "action_ask_about_house"

    async def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        house_name = next(tracker.get_latest_entity_values("house"), None)
        house_list = graph.query_house(house_name)

        if not house_name:
            api_instance.ask(tracker.events, dispatcher)
            return []

        if not house_list:
            dispatcher.utter_message("不好意思，我不清楚你问的" + (house_name if house_name else "") + "是什么团体或者国家。", attachment="finish")
            return []

        house_node = house_list[0]["h"]
        message = (house_name + ("是" + house_node["des"] + "\n"))

        owned_person_list = graph.query_house_persons(house_name)

        if owned_person_list:
            message += "这些人属于" + house_name + "：\n"

            for record in owned_person_list:
                message += record["name"] + "\n"

        api_instance.optimize_response(tracker.events, message, dispatcher)
        return []
